package service

import (
	"context"
	"encoding/json"
	"github.com/gogf/gf/v2/container/gmap"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"go-websocket/internal/dao"
	"go-websocket/internal/model/entity"
	"go-websocket/utility"
)


var (
	Users = gmap.IntAnyMap{}
)


func Conn(r *ghttp.Request) {

	ws, err := r.WebSocket()//将请求转为websocket
	if err != nil {
		g.Log().Error(context.TODO(), "websocket打开错误", err)
		return
	}
	for {
		msgType, msg, err := ws.ReadMessage()//读取

		if err != nil {
			g.Log().Error(context.TODO(), "websocket读取错误", err)
			return
		}
		var receiveData g.Map

		// 将字节数组解析为 map
		err = json.Unmarshal(msg, &receiveData)
		if err != nil {
			g.Log().Error(context.TODO(), "json解析错误", err)
			return
		}

		switch receiveData["action"] {
			case "checkToken":
				go onMessage(ws, msgType, receiveData)
				fallthrough
			case "ping":
				go pingPong(ws, msgType,receiveData, msg)
			default:
				return
		}

	}
	
}





func onMessage(ws *ghttp.WebSocket, msgType int, receiveData map[string]interface{})  {

	//校验token
	token := utility.VerifyToken(receiveData["data"].(string))

	if token == nil {
		//TODO 删除下线处理
		g.Log().Error(context.TODO(), "token错误")
		return
	}


	var userId int
	if f, ok  := token["user_id"].(float64); ok {

		userId = int(f)
	} else {
		g.Log().Error(context.TODO(), "用户数据错误")
		return
	}

	var userInfo *entity.TxzhUser
	userModel := dao.TxzhUser.Ctx(context.TODO())
	err := userModel.Where("id", userId).Scan(&userInfo)

	if err != nil {
		g.Log().Error(context.TODO(), "user表查询错误", err)
		return
	}

	//存储用户信息

	cli := &Client{
		UserId: userId,
		User: userInfo,
		Ws: ws,
	}

	hasUser := Users.Get(cli.UserId)


	if hasUser != nil {
		//TODO 删除下线处理
	}

	Users.Set(cli.UserId, cli)//存储用户

	sendData := g.Map{
		"action":"checkToken",
		"data": map[string]int{
			"err":0,
		},
	}

	marshal, _ := json.Marshal(sendData)
	if err := ws.WriteMessage(msgType, marshal); err != nil {
		g.Log().Error(context.TODO(), "websocket发送错误", err)
		return
	}

}

func onClose()  {
	
}



func pingPong(ws *ghttp.WebSocket, msgType int,receiveData map[string]interface{}, msg []byte)  {


	md := g.Model("user")
	_, err := md.One()
	if err != nil {
		g.Log().Error(context.TODO(), "user表查询错误", err)
		return
	}

	//校验token
	token := utility.VerifyToken(receiveData["data"].(string))

	if token == nil {
		//TODO 删除下线处理
		g.Log().Error(context.TODO(), "token错误", err)
		return
	}

	if err := ws.WriteMessage(msgType, msg); err != nil {
		g.Log().Error(context.TODO(), "websocket发送错误", err)
		return
	}

}
